<template>
  <div v-loading="loadingAll">
    <div class="create__content">
      <el-steps :active="stepsActive" simple style="margin: 20px 0;">
        <el-step title="编辑基本信息" icon="el-icon-edit"></el-step>
        <el-step title="确认课表" icon="el-icon-check"></el-step>
      </el-steps>
      <el-form v-if='editing' :model="goodsForm" :rules="rules" ref="goodsForm" label-width="100px">
        <el-form-item label="显示端" required>
          <span>升学在线APP</span>
        </el-form-item>
        <el-form-item label="商品名称" prop="commodityName">
          <el-input v-model="goodsForm.commodityName" placeholder="请输入商品名称" maxlength="30"></el-input>
        </el-form-item>
        <!-- <el-form-item label="商品简介" prop="commodityDesc">
            <el-input v-model="goodsForm.commodityDesc" placeholder="商品简介 (微信分享给好友时会显示这里的文案)"></el-input>
          </el-form-item> -->
        <el-form-item label="商品权重" prop="weights">
          <!-- <el-input v-model="goodsForm.weights" placeholder="请输入商品权重" type='number'></el-input> -->
          <el-input-number v-model="goodsForm.weights" :min="0" label="请输入商品权重"></el-input-number>
        </el-form-item>
        <el-form-item label="推荐类型" prop="sign">
          <el-select v-model="goodsForm.sign">
            <el-option :value='null' label="--"></el-option>
            <el-option v-for="type in signList" :key="type.id" :label="type.typeName" :value="type.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否为广告课程" prop="isAd">
          <el-select v-model="goodsForm.isAd">
            <el-option v-for="ad in isAdList" :key="ad.id" :label="ad.name" :value="ad.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否为vip商品" prop="isVip">
          <el-select v-model="goodsForm.isVip">
            <el-option v-for="vip in isVipList" :key="vip.id" :label="vip.name" :value="vip.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择年级" prop="gradeId">
          {{getGradesList}}
          <el-select v-model="goodsForm.gradeId" @change='gradeChange'>
            <el-option :value='0' label="--"></el-option>
            <el-option v-for="grade in gradeList" :key="grade.id" :label="grade.gradeName" :value="grade.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择科目" prop="subjectId" v-show='goodsForm.gradeId'>
          <el-select v-model="goodsForm['subjectId']">
            <el-option :value='0' label="--"></el-option>
            <el-option v-for="subject in getSubjectsList" :key="subject.id" :label="subject.subjectName" :value="subject.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属主题" prop="topicId">
          {{getTopicsList}}
          <el-select v-model="goodsForm.topicId">
            <el-option v-for="topic in topicList" :key="topic.id" :label="topic.topicName" :value="topic.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择专家" prop="professorId">
          {{getProfessorsList}}
          <el-select v-model="goodsForm.professorId" >
            <el-option :value='null' label="--"></el-option>
            <el-option v-for="professor in professorList" :key="professor.id" :label="professor.name" :value="professor.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品配图" prop="picList" class='unlimtFormItem uploadContainer' v-loading="Loading">
          <form action="" enctype="multipart/form-data">
            <input type="file" accept="image/*" name="file" id="file" ref="file" class="inputfile" multiple v-on:change="changepic($event)" />
            <label for="file" class='btn-success'>添加图片</label> 
            <p class="image_describe">注：最多上传三张：建议尺寸 像素 654*492</p>
            <ul class="show_list">
              <li 
                class="drag-field image_item" v-for="(item, index) of fileList"  :key="index" :data-index="index" :draggable="true"
                @drop="drop"
                @dragover.prevent
                @dragstart="dragstart"
                @dragend="dragend($event, item)"
              >
                <!-- <img :src="item.url" ref="show" id="show" width="200"> -->
                <span class="back_img" :style="'background-image:url('+item.url+');'"></span>
                <a :title="item.name">{{item.name}}</a>
                <label class="label_yes">
                  <i class="icon_success"></i>
                </label>
                <i class="icon_close" @click="handleRemovePic(item)"></i>
              </li>
            </ul>
          </form>
        </el-form-item> 

        <el-form-item label="商品规格" prop='lessonIds'>
          <!-- <el-form-item label="商品规格" prop=''> -->

          <!-- <el-input v-model="goodsForm.lessonIds" type='text' style='display:none'></el-input> -->
          <el-checkbox-group v-model="goodsForm.lessonIds" style='display:none'></el-checkbox-group>
          <el-button size="mini" type="primary" @click="typeDialogVisible = true">选择课程</el-button>
          <el-button v-if='lessonData.length>0' size="mini" type="primary" @click="deleteAllLesson">重置</el-button>
          <div v-if='lessonData.length>0'>
            <el-tag type='info' closable v-for='(lesson,index) in lessonData' :key='index' @close="deleteLesson(index)" style="margin-right:12px">{{lesson.lessonTopic}}</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="商品详情" prop="details">
          <Tinymce :height='30' :value='goodsForm.details' ref="editor" v-model="goodsForm.details" />
        </el-form-item>

        <el-form-item>
          <el-button :disabled='preventSumit' type="success" @click="toPreviewCommodity">下一步</el-button>
        </el-form-item>
      </el-form>
      <div v-if='!editing'>
        <lesson-list :is-preview-lessons='isPreviewCommodity' :default-preview-lessons='lessonData'></lesson-list>
        <el-button @click="toEditCommodity" type='success'>上一步</el-button>
        <el-button type='primary' @click='createCommodity'>{{toBeEditedGoodId ? '保存' :'上架'}}</el-button>
      </div>
    </div>
    <!--添加商品规格对话框-->
    <el-dialog v-if="typeDialogVisible" title="选择课程" width="50%" top="10vh" :visible.sync="typeDialogVisible" :modal='false'>
      <lesson-list v-on:addlessontocommodity='chooseLesson' :is-create-commodity='isCreateCommodity' :default-selected-lessons='lessonData' :default-lesson-type='lessonType'></lesson-list>
    </el-dialog>
  </div>
</template>

<script>
import lessonList from '../curriculum/list'
import Tinymce from '@/components/Tinymce'
import { getToken } from '@/utils/auth' // 验权
import { getGradeList } from '@/api/grade'
// import { getSubjectList } from '@/api/subject'
import { getAddTopList as getTopicList } from '@/api/course'
import { createGood, getGoodDetail, modifyGood, upload, getProfessorList } from '@/api/goods'
import { getLessonsList } from '@/api/curriculum'

export default {
  name: 'articleDetail',
  props: {
    commodityId: {
      type: Number,
      required: false
    }
  },
  components: { lessonList, Tinymce },
  data() {
    const validateRequire = (rule, value, callback) => {
      this.goodsForm[rule.field] = this.goodsForm[rule.field].trim()
      callback()
    }
    return {
      Loading: false,
      startIndex: 0,
      targetIndex: 0,
      toBeEditedGoodId: this.commodityId,
      headers: {},
      stepsActive: 1,
      gradeList: [],
      professorList: [],
      subjectList: [],
      topicList: [],
      fileList: [],
      isCreateCommodity: true,
      lessonData: [], //课程列表
      lessonType: 1,
      isPreviewCommodity: true,
      typeDialogVisible: false,
      editing: true,
      loadingAll: false,
      preventSumit: false,
      goodsForm: {
        // commodityDesc: '', //商品简介 required
        commodityName: '', // 商品名称 required
        commodityType: 1,
        details: '', //商品详情
        gradeId: null,
        id: 0,
        lessonIds: [], // 关联课程 id required
        picList: [], // 商品配图 required
        skuDesc: 'default empty', //商品规格描述
        subjectId: null, // 科目
        topicId: null, // 主题
        weights: 100,
        sign: null, // 推荐类型
        isAd: null, // 是否为广告课程
        isVip: null, // 是否为vip课程
        professorId: [], //关联专家id
        professorName: '' //关联专家name
      },
      signList: [{
        id: '新',
        typeName: '新课'
      }, {
        id: '荐',
        typeName: '推荐'
      }, {
        id: '热',
        typeName: '火爆'
      }],
      isAdList: [{
        id: 1,
        name: '是',
        type: 1
      }, {
        id: 2,
        name: '否',
        type: 0
      }],
      isVipList: [{
        id: 1,
        name: '是',
        type: 1
      }, {
        id: 2,
        name: '否',
        type: 0
      }],
      rules: {
        commodityName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        // commodityDesc: [
        //   { required: true, message: '请输入商品简介', trigger: 'blur' },
        //   { validator: validateRequire,trigger:'blur' }
        // ],
        topicId: [{ required: true, message: '请选择课程所属主题', trigger: 'change' }],
        picList: [{ required: true, message: '请添加商品配图', trigger: 'change' }],
        lessonIds: [{ type: 'array', required: true, message: '请选择课程', trigger: 'change' }],
        weights: [{ required: true, message: '请输入商品权重', trigger: 'change' }],
        details: [{ validator: validateRequire, trigger: 'change' }],
        isAd: [{ required: true, message: '请选择是否为广告商品', trigger: 'change' }],
        isVip: [{ required: true, message: '请选择是否为VIP商品', trigger: 'change' }]
      }
    }
  },
  created() {
    this.headers = { accessToken: getToken() }
    if (this.toBeEditedGoodId) {
      getGoodDetail(this.toBeEditedGoodId).then(res => {
        const { code, data, message } = res
        if (code == 0) {
          this.goodsForm = Object.assign({}, this.goodsForm, data)
          const { lessons, picList, commodityType } = data
          const pics = []
          const lessonIds = []
          picList.map(e => {
            pics.push({ name:e, url:e })
          })
          lessons.map(e => {
            lessonIds.push(e.id)
          })
          this.fileList = pics
          this.lessonData = lessons
          this.lessonType = commodityType
          this.goodsForm['lessonIds'] = lessonIds
          // this.$set(this,'goodsForm',data)
        } else {
          this.$message({
            message,
            type: 'warning'
          })
        }
      })
    }
  },
  methods: {
    // 上传图片
    changepic(event) {
      const obj = {}
      const _that = this
      if (_that.fileList.length < 3) {
        // 获取file文件数据
        const objUrl = event.target.files[0]
        // 新建一个formData对象，通过append方法将file文件数据存入其中
        const fd = new FormData()
        fd.append('file', objUrl)
        this.Loading = true
        upload(fd).then(res => {
          if (res.code == '0') {
            obj.url = res.data.picUrlList[0]
            obj.name = res.data.picUrlList[0]
            _that.fileList.push(obj)
            _that.goodsForm['picList'].push(res.data.picUrlList[0])
            _that.Loading = false
          }
        })
      } else {
        alert('最多上传三张图片！')
      }
    },
    // 删除图片
    handleRemovePic(item) {
      const newArr = this.fileList.filter(x => {
        return x != item
      })
      this.fileList = newArr
      const newPicList = this.goodsForm.picList.filter(x => {
        return item.url != x
      })
      this.goodsForm.picList = newPicList
    },
    toPreviewCommodity() {
      if (this.goodsForm.picList.length == 0) {
        this.$message({
          message: '请至少上传一张图片!',
          type: 'warning'
        })
        return false
      }
      this.$refs.goodsForm.validate(valid => {
        if (valid) {
          if (this.goodsForm.lessonIds.length == 0) {
            this.createCommodity()
          } else {
            this.editing = false
            this.stepsActive = 2
          }
        } else {
          this.$message({
            message: '请完善商品信息!',
            type: 'warning'
          })
          return false
        }
      })
    },
    toEditCommodity() {
      this.editing = true
      this.stepsActive = 1
    },
    opreateCommodity(opreateFun) {
      console.log('goodsForm', this.goodsForm)
      this.goodsForm.details = this.goodsForm.details.trim()
      opreateFun(this.goodsForm)
        .then(res => {
          const { code } = res
          const message = this.toBeEditedGoodId ? '修改成功!' : '上架成功!'
          if (code == 0) {
            this.$message({
              message,
              type: 'success'
            })
            this.$router.push('list')
            this.loadingAll = false
            if (this.toBeEditedGoodId) {
              this.$emit('edit-complete', true)
            }
          }
        })
        .catch(rej => {
          this.loadingAll = false
        })
    },
    createCommodity() {
      this.loadingAll = true
      const fun = this.toBeEditedGoodId ? modifyGood : createGood
      this.opreateCommodity(fun)
    },
    // 图片拖拽
    drop(event) {
      this.targetIndex = parseInt(event.target.parentElement.dataset.index)
    },
    dragstart(event) {
      this.startIndex = parseInt(event.target.dataset.index)
      console.log('起始位置', this.startIndex)
    },
    dragend(event, item) {
      console.log('event', event)
      event.dataTransfer.clearData()
      if (event.target.nodeName == 'LI') {
        this.fileList.splice(this.startIndex, 1)
        this.fileList.splice(this.targetIndex, 0, item)
        const newList = []
        for (const item of this.fileList) {
          newList.push(item.url)
        }
        this.goodsForm.picList = newList
      } else if(event.target.nodeName == 'IMG') {
        alert('请按住空白区域拖拽')
      }
    },

    handleUploadSuccess(rst){
      const { code, data:{ picUrlList } } = rst
      const { goodsForm } = this
      if(code == 0){
        goodsForm['picList'].push(picUrlList[0])
      }
    },
    handlePreview(file) {
    },
    handleClose(tag) {
      this.multipleSelection.splice(this.multipleSelection.indexOf(tag), 1)
    },
    handleRemove(file, fileList) {
      const { goodsForm:{ picList } } = this
      picList.splice(picList.indexOf(file['url']), 1)
      this.goodsForm.picList = picList
    },
    uploadSuccess(response, file, fileList) {
      const { code, data: { picUrlList }, message } = response
      if (code == 0) {
        this.fileList = [{ name: picUrlList[0], url: picUrlList[0] }]
        this.$set(this.goodsForm, 'pic', picUrlList[0])
        console.log('goodsForm', this.goodsForm)
      } else {
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '上传失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
      this.preventSumit = false
    },
    chooseLesson(lessonData, lessonType) {
      this.typeDialogVisible = false
      this.goodsForm['commodityType'] = lessonType
      this.lessonData = []
      this.lessonData = this.lessonData.concat(lessonData)
      this.lessonType = lessonType
      this.formatLessonIds()
    },
    deleteLesson(index) {
      this.lessonData.splice(index, 1)
      this.formatLessonIds()
    },
    deleteAllLesson() {
      this.$set(this, 'lessonData', [])
      this.formatLessonIds()
    },
    getlessonListAll() {
      if (!this.toBeEditedGoodId) { return '' }
      const params = {
        tagOrTopic: '',
        pageNo: 1,
        pageSize: Infinity,
        startDate: '',
        endtDate: ''
      }
      getLessonsList(params).then(res => {
        const { code, data: { list } } = res
        if (code == 0) {
          Array.from(list, info => {
            if (this.goodsForm.lessonIds.includes(info.id)) {
              this.lessonData.push(info)
            }
          })
        }
      })
    },
    formatLessonIds() {
      const lessonDataLength = this.lessonData.length
      const lessonData = this.lessonData
      this.goodsForm.lessonIds = Array.from(lessonData, lesson => lesson.id)
      // this.$set(this.goodsForm,'lessonIds',Array.from(lessonData,lesson=>lesson.id))
    },

    professorChange() {
      this.goodsForm.professorId = 0
    },

    gradeChange() {
      this.goodsForm.subjectId = 0
      // this.getSubjectsList(newGradeId)
    }
  },
  computed: {
    getGradesList() {
      getGradeList().then(res => {
        const { code, data } = res
        if (code == 0) {
          this.gradeList = data
        }
      })
    },

    getProfessorsList() {
      getProfessorList().then(res => {
        const { code, data } = res
        if (code == 0) {
          this.professorList = data
        }
      })
    },

    getTopicsList() {
      getTopicList().then(res => {
        const { code, data } = res
        if (code == 0) { this.topicList = data }
      })
    },
    getSubjectsList() {
      const gradeId = this.goodsForm.gradeId
      this.gradeList.forEach(grade => {
        if (grade.id == gradeId) {
          this.subjectList = grade.subjects
        }
      })
      return this.subjectList
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.imgBox {
  width: 330px;
  height: 195px;
  overflow: hidden;
  img {
    width: 100%;
  }
}
.el-input-number {
  width: 200px;
}
.unlimtFormItem.uploadContainer {
  .el-upload__tip,
  .el-form-item__error {
    margin-left: 110px;
  }
}
.create__content {
  width: 688px;
  margin: 0 auto;
}
.inputfile {
  z-index: -11111;  width: 0px;  height: 1px;
}
.btn-success {
  background: #409EFF;
  font-size: 12px;
  color: #fff;
  padding: 9px 15px;
  border-radius: 3px;
  font-weight: normal;
}
.btn-success:hover {
  cursor: pointer;
  background: #66b1ff;
}
.image_describe {
  margin-left: 110px;
  font-size: 12px;
  color: #606266;
}

.show_list {
  list-style: none;
  padding-left: 0;
  .image_item {
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin-top: 10px;
    position: relative;
    padding: 10px;
    height: 92px;
    overflow: hidden;
    display: flex;
    justify-content: flex-start;
    // img {
    .back_img {  
      display: inline-block;
      vertical-align: middle;
      display: inline-block;
      width: 70px;
      height: 70px;
      position: relative;
      z-index: 1;
      margin-right: 20px;
      background-size: 100% 100%;
    }
    a {
      line-height: 70px;
      margin-top: 0;
      color: #606266;
      display: block;
      margin-right: 40px;
      overflow: hidden;
      padding-left: 4px;
      text-overflow: ellipsis;
      -webkit-transition: color .3s;
      transition: color .3s;
      white-space: nowrap;
    }
    .label_yes {
      position: absolute;
      right: -17px;
      top: -7px;
      display: block;
      width: 46px;
      height: 26px;
      background: #13ce66;
      text-align: center;
      -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
      -webkit-box-shadow: 0 1px 1px #ccc;
      box-shadow: 0 1px 1px #ccc;
      .icon_success {
        display: inline-block;
        color: #fff;
        font-size: 12px;
        -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
      }
      .icon_success:before {
        content: '√';
      }
    }
    .icon_close {
      position: absolute;
      top: -5px;
      right: 10px;
      cursor: pointer;
      opacity: .75;
      color: #606266;
    }
    
  }
  .image_item:hover {
    .label_yes {
      display: none;
    }
    .icon_close:before{
      content: "X";
    }
  }
}
.drag-field{
    height: 10rem;
    box-sizing: border-box;
    background-color: #eee;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

</style>